/**
 * 
 */
package com.revenco.bi.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.json.JSONArray;
import org.json.JSONObject;
import org.nutz.dao.QueryResult;
import org.nutz.dao.entity.Record;
import org.nutz.dao.pager.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.revenco.bi.dao.TnChartParamsDao;
import com.revenco.bi.model.TnChartParams;
import com.revenco.bi.model.TnTableColumnRelation;
import com.revenco.bi.model.userbean.CFieldsBean;
import com.revenco.bi.model.userbean.CQueryBean;
import com.revenco.bi.model.userbean.ConditonVal;
import com.revenco.bi.model.userbean.ConditonValList;
import com.revenco.bi.service.TnChartParamsService;
import com.revenco.bi.service.TnOthtableMaintableRelaService;
import com.revenco.bi.util.JsonBinder;

/**
 * @author LingJun
 * @version $Revision:1.0.0, 2014年1月27日 上午10:56:29
 */
@Service
public class TnChartParamsServiceImpl implements TnChartParamsService {
	@Autowired
	private TnChartParamsDao tnChartParamsDao;
	@Autowired
	private TnOthtableMaintableRelaService tomrs;
	JsonBinder binder = new JsonBinder();

	// 报表筛选数据
	CQueryBean cField;
	CFieldsBean cBean;

	public void save(String cFields, String chartId) {
		// 报表筛选数据
		cField = binder.fromJson(cFields, CQueryBean.class);
		int cNum = cField.getCONDITION().length;
		TnChartParams tParams = new TnChartParams();
		for (int i = 0; i < cNum; i++) {
			cBean = cField.getCONDITION()[i];
			// 图表参数表信息存储
			tParams.setParamsId(new Date().getTime());
			tParams.setChartId(chartId);
			tParams.setParamCd(cBean.getName());
			tParams.setParamName(cBean.getParamName());
			tParams.setParamType(cBean.getParamType());
			tParams.setDefaultValue(cBean.getDefaultValue());
			tParams.setDefaultText(null);
			tParams.setDataType(cBean.getColType());
			tParams.setParamValueFromField(null);
			tParams.setParamTextFromField(null);
			tParams.setParamTextvalueFromTableNam(cBean.getTableName());
			tParams.setOpType(cBean.getOperator());
			// 暂定为值操作类型
			// tParams.setOrderNum(orderNum); //多个参数时应有顺序
			this.tnChartParamsDao.saveTnChartParams(tParams);
		}
	}

	public void update(String cFields, String paramId) {
		// 报表筛选数据
		cField = binder.fromJson(cFields, CQueryBean.class);
		tnChartParamsDao.delChartParamsByIdName(paramId);
		int cNum = cField.getCONDITION().length;
		
		for (int i = 0; i < cNum; i++) {
			cBean = cField.getCONDITION()[i];
			TnChartParams tParams = new TnChartParams();
			tParams.setParamsId(new Date().getTime());
			tParams.setChartId(paramId);
			tParams.setParamCd(cBean.getName());
			tParams.setParamName(cBean.getParamName());
			tParams.setParamType(cBean.getParamType());
			tParams.setDefaultValue(cBean.getDefaultValue());
			tParams.setDefaultText(null);
			tParams.setDataType(cBean.getColType());
			tParams.setParamValueFromField(null);
			tParams.setParamTextFromField(null);
			tParams.setParamTextvalueFromTableNam(cBean.getTableName());
			tParams.setOpType(cBean.getOperator());
			// 暂定为值操作类型
			// tParams.setOrderNum(orderNum); //多个参数时应有顺序
			this.tnChartParamsDao.saveTnChartParams(tParams);
		}
	}

	public String getDefaultValue(String table, String column, String columnId,
			String colType, Pager pager) {
		ConditonValList cvl = new ConditonValList();

		if (colType.equals("4") || colType.equals("3")) {
			cvl = getConditonValFour(table, column, colType, pager);
		} else if (colType.equals("1")) {
			cvl = getConditonValOne(columnId, pager);
		}
		String cvl2Json = binder.toJson(cvl);
		return cvl2Json;
	}

	/**
	 * 日期json
	 * 
	 * @param table
	 * @param column
	 * @param colType
	 * @param pager
	 * @return
	 */
	public ConditonValList getConditonValFour(String table, String column,
			String colType, Pager pager) {
		ConditonValList cvlFour = new ConditonValList();
		QueryResult qr = this.tnChartParamsDao.getDefaultValue(table, column,
				pager);
		@SuppressWarnings("unchecked")
		List<Record> defaultValList = (List<Record>) qr.getList();
		cvlFour.setCount(qr.getPager().getRecordCount());
		int size = defaultValList.size();
		if (size < 1) {
			return null;
		}
		ConditonVal[] cvArray = new ConditonVal[size];
		for (int i = 0; i < size; i++) {
			Record r = defaultValList.get(i);
			ConditonVal cv = new ConditonVal();
			cv.setName(r.get(column).toString());
			cv.setValue(r.get(column).toString());
			cvArray[i] = cv;
		}
		cvlFour.setConditonVal(cvArray);
		return cvlFour;
	}

	/**
	 * 维表json
	 * 
	 * @param columnId
	 * @param pager
	 * @return
	 */
	public ConditonValList getConditonValOne(String columnId, Pager pager) {
		ConditonValList cvlOne = tomrs.getDemensionDataByColumnIdQr(columnId,pager);
		return cvlOne;
	}

	public List<TnChartParams> getChartParams(String chartId) {
		return this.tnChartParamsDao.getChartParamsList(chartId);
	}

	public void deleteByChartId(String chartId) {
		this.tnChartParamsDao.deleteByChartId(chartId);
	}

	/**
	 * 保存TnTableColumnRelation表信息
	 * @param mulRelationData
	 * @param chartId
	 */
	public void saveTnTableColumnRelation(String mulRelationData, String chartId) {
		mulRelaTable(mulRelationData, chartId);
	}
	
	/**
	 * 解析多表关联中的表名和字段名，插入到TnTableColumnRelation表中
	 * @param mulRelationData
	 * @param chartId
	 */
	private void mulRelaTable(String mulRelationData, String chartId) {
		if (!mulRelationData.equals("{}")) {
			JSONObject rootObj;
			rootObj = new JSONObject(mulRelationData);
			JSONArray array = rootObj.getJSONArray("COLUMN");
			for (int i = 0; i < array.length(); i++) {
				JSONObject temp = array.getJSONObject(i);
				String leftTable = getTable((String) temp.get("first_Column"));
				String leftColumn = getColumn((String) temp.get("first_Column"));
				String rightTable = getTable((String) temp.get("last_Column"));
				String rightColumn = getColumn((String) temp.get("last_Column"));
				String id = UUID.randomUUID().toString().replace("-", "").toUpperCase().substring(0, 11);
				TnTableColumnRelation table = new TnTableColumnRelation(); 
				table.setId(id);
				table.setMainTableId(leftTable);
				table.setMainColumnId(leftColumn);
				table.setRelaTableId(rightTable);
				table.setRelaColumnId(rightColumn);
				table.setRelationType("0"); // 表示“=”
				table.setChartId(chartId);
				this.tnChartParamsDao.saveTnTableColumnRelation(table);
			} 
		}
	}
	
	/**
	 * 获取多表关联中的表名
	 * @param relaColumn(设置多表关联时后台传递的first_Column或last_Column)
	 * @return table
	 */
	public String getTable(String relaColumn) {
		String table = relaColumn.split("=")[0];
		return table;
	}
	
	/**
	 * 获取多表关联中的表字段
	 * @param relaColumn(设置多表关联时后台传递的first_Column或last_Column)
	 * @return column
	 */
	public String getColumn(String relaColumn) {
		return relaColumn.split("=")[1];
	}
}
